# 获取脚本的绝对路径
set script_path [file normalize [info script]]
puts "Script path: $script_path"

# 从脚本路径反推.runs目录
set script_dir [file dirname $script_path]
set proj_root [file dirname [file dirname $script_dir]]
puts "Project root directory: $proj_root"

# 查找所有.runs目录
set runs_dirs [glob -nocomplain [file join $proj_root "*.runs"]]
puts "Found runs directories: $runs_dirs"

# 查找包含impl_*的子目录并找到最新的.bin文件
set latest_bin ""
set latest_time 0
foreach runs_dir $runs_dirs {
    set impl_dirs [glob -nocomplain [file join $runs_dir "impl_*"]]
    foreach impl_dir $impl_dirs {
        set bin_files [glob -nocomplain [file join $impl_dir "*.bin"]]
        if {[llength $bin_files] > 0} {
            foreach bin $bin_files {
                set mtime [file mtime $bin]
                if {$mtime > $latest_time} {
                    set latest_bin $bin
                    set latest_time $mtime
                }
            }
        }
    }
}
puts "Latest bin file: $latest_bin"

# 验证bin文件是否存在且可读
if {$latest_bin == ""} {
    error "No bin files found in any impl_* directories"
}
if {![file exists $latest_bin]} {
    error "Latest bin file $latest_bin does not exist"
}
if {![file readable $latest_bin]} {
    error "Latest bin file $latest_bin is not readable"
}

# 提取compile_time.v中的日期
set compile_time_file [file join $script_dir "../sources_1/new/compile_time.v"]
puts "Compile time file: $compile_time_file"
if {![file exists $compile_time_file]} {
    error "Compile time file $compile_time_file does not exist"
}
set fp [open $compile_time_file r]
set content [read $fp]
close $fp
# 提取双引号中的内容
regexp {".*"} $content date_str
# 去除首尾双引号和多余空格
set date_str [string trim $date_str "\" "]
# 格式化为YYYYMMDD_HHMMSS
set year [string range $date_str 0 3]
set month [string range $date_str 5 6]
set day [string range $date_str 8 9]
set hour [string range $date_str 11 12]
set minute [string range $date_str 14 15]
set second [string range $date_str 17 18]
set compile_date "${year}${month}${day}_${hour}${minute}${second}"
puts "Extracted compile date: $compile_date"

# 使用PowerShell的Get-FileHash计算MD5值
puts "Calculating MD5 for $latest_bin using PowerShell"
# 确保路径使用Windows格式
set latest_bin [file nativename $latest_bin]
if {[catch {set md5sum [exec powershell -Command "(Get-FileHash -Algorithm MD5 -Path '$latest_bin').Hash"]} err]} {
    error "Failed to calculate MD5: $err"
}
# 转换为小写以保持一致性
set md5sum [string tolower $md5sum]
puts "MD5 calculated: $md5sum"

# 目标文件名
set target_file "XXXX_${compile_date}_fpga_${md5sum}.bin"

# 删除过时的master_*.bin文件（在源文件目录下）
set old_files [glob -nocomplain [file join [file dirname $latest_bin] "XXXX_*.bin"]]
foreach old_file $old_files {
    if {[file exists $old_file]} {
        puts "Deleting old file: $old_file"
        if {[catch {file delete $old_file} err]} {
            puts "Warning: Failed to delete $old_file: $err"
        }
    }
}

# 复制最新的bin文件到源文件目录并重命名
puts "Copying $latest_bin to $target_file"
set target_path [file join [file dirname $latest_bin] $target_file]
if {[catch {file copy -force $latest_bin $target_path} err]} {
    error "Failed to copy $latest_bin to $target_path: $err"
}

puts "Successfully copied $latest_bin to $target_path"